import React, { useReducer } from 'react'

export default function ReducerCom() {
  //调用 useReducer 函数. state 状态值,  action 操作对象
  // action 是一个对象 {type: 操作类型, payload: 操作需要的数据}   payload 载荷
  // {type: 'incre', payload: 2}
  // {type: 'decre', payload: 5}
  // {type: 'xxx', payload: 5}
  // dispatch 
  let [state, dispatch] = useReducer((state, action) => {
    //根据 action 的值, 更新 state 的值
    switch(action.type){
      //新增
      case 'incre':
        //返回的返回值, 将作为状态的新的值.  setCount(v => v + 1);
        return state + action.payload;
      //减少操作
      case 'decre': 
        return state - action.payload;
      //其他情况
      default: 
        return state;
    }
  }, 0);

  return (
    <div>
      <h2>{state}</h2>
      <button onClick={() => {
        //调用dispatch
        dispatch({type: 'incre', payload: 100});
      }}>新增</button>
      <button onClick={() => {
        //调用dispatch
        dispatch({type: 'decre', payload: 50});
      }}>减少</button>
    </div>
  )
}
